<template>
    <div class="newPrimaryClass">
        <div class="newPrimaryClass_top">
			<div class="into_index">首页<i class="el-icon-close"></i></div>
			<div class="current">{{text}}资讯<i class="el-icon-close"></i></div>
		</div>
        <!-- 商家类型与返回 -->
        <div class="newPrimaryClass_type">
            <div>资讯列表/<span class="text">{{text}}资讯</span></div>
            <el-button @click="toBack" type="success">返回</el-button>
        </div>

        <!-- tabs -->
        <div style="background:#fff;padding:0 20px;">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="资讯信息" name="1"></el-tab-pane>
            <el-tab-pane label="转发列表" v-if="id" name="2">
              <forward-table ref="forwardFn" :informationId="id"></forward-table>
            </el-tab-pane>
            <el-tab-pane label="点赞列表" v-if="id" name="3">
              <support-table ref="supportFn" :informationId="id"></support-table>
            </el-tab-pane>
            <el-tab-pane label="评论列表" v-if="id" name="4">
              <comment-list ref="commentFn" :informationId="id"></comment-list>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 新增分类信息 -->
        <div class="classInfo" v-if="activeName=='1'">
            <div class="className">
                <span>资讯标题</span>
                <input type="text" maxlength="150" v-model="tit" placeholder="请输入">
            </div>
            <div class="mediaType">
              <span>资讯类型</span>
              <el-radio v-model="mediaType" label="0">文字</el-radio>
              <el-radio v-model="mediaType" label="1">图片</el-radio>
              <el-radio v-model="mediaType" label="2">视频</el-radio>
            </div>
            <div class="classImg" v-if="mediaType=='1'">
                <span>主图</span>
                <el-upload
                    action="/api/client/base/uploadfile"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    ref="upload"
                    :on-remove="handleRemove"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :auto-upload="true"              
                    :limit="50" 
                    :headers="myHeaders"
                    :file-list="fileList"           
                    accept="image/jpeg, image/jpg, image/gif, image/png"    
                    multiple>
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </div>
            <div class="videoBox" v-if="mediaType=='2'">
              <span>视频</span>
              <div class="item">
                <el-upload
                    class="avatar-uploader el-upload--text avatar"
                    action="/api/client/base/uploadfile"
                    :show-file-list="false"
                    :on-success="handleVideoSuccess"
                    :before-upload="beforeUploadVideo"
                    :on-progress="uploadVideoProcess">
                    <video
                    v-if="videoUrl != '' && videoFlag == false"
                    :src="videoUrl"
                    controls="controls"
                    >
                    您的浏览器不支持视频播放
                    </video>
                    <i v-if="videoUrl == '' && videoFlag == false"
                    class="el-icon-plus avatar-uploader-icon"
                    ></i>
                    <el-progress
                    v-if="videoFlag == true"
                    type="circle"
                    :format="format"
                    :percentage="videoUploadPercent"
                    style="margin-top:30px;"
                    ></el-progress>
                    <div class="uploadLabel" v-if="videoUrl!==''" @click.stop="closeVideo">
                        <i class="el-icon-close"></i>
                    </div>
                </el-upload>
              </div>
            </div>
            <div class="classShow">
                <span>发布对象：</span>
               <div>
                <el-checkbox-group v-model="checkList">
                    <!-- <el-checkbox label="all">全部</el-checkbox> -->
                    <el-checkbox label="shop">商家</el-checkbox>
                    <el-checkbox label="designer">设计师</el-checkbox>
                    <el-checkbox label="builder">施工队</el-checkbox>
                    <el-checkbox label="decoration">装修公司</el-checkbox>
                    <el-checkbox label="master">创业主</el-checkbox>
                    <el-checkbox label="promoter">创业精英</el-checkbox>
                    <el-checkbox label="steward">超级管家</el-checkbox>
                    <el-checkbox label="user">用户端小程序</el-checkbox>
                </el-checkbox-group>
                   
               </div>
            </div>
            <div class="classShow" style="margin-top:0;">
                <span>发布类别：</span>
               <div>
                <el-checkbox-group v-model="categoryList">
                    <!-- <el-checkbox label="all">全部</el-checkbox> -->
                    <el-checkbox label="1">热门</el-checkbox>
                    <el-checkbox label="2">精选</el-checkbox>
                    <el-checkbox label="3">必看</el-checkbox>
                    <el-checkbox label="4">推荐</el-checkbox>
                    <el-checkbox label="5">行情</el-checkbox>
                </el-checkbox-group>
               </div>
            </div>
            <!-- 上下架 -->
            <div class="" style="margin-bottom:40px;">
              <span>是否上架</span>
              <el-radio v-model="status" label="0">否</el-radio>
              <el-radio v-model="status" label="1">是</el-radio>
            </div>
            <!-- 卖场选择 -->
            <div class="" style="margin-bottom:40px;">
              <span>选择卖场</span>
              <el-select v-model="marketId" clearable @change="selectMarket" filterable placeholder="请选择卖场">
                <el-option
                  v-for="item in marketList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <div class="editor">
                <span>资讯内容</span>
                <div style="width:600px;"><!--上传图片时得加载画面-->
					<VueEditor style="width: 100%;" 
                        v-loading="editorLoading"
                        element-loading-text="图片上传中"
                        element-loading-background="rgba(0, 0, 0, 0.5)"
						useCustomImageHandler 
						@image-added="handleImageAdded"
                        :editorToolbar="customToolbar"
						v-model="detail">
                    </VueEditor>
    			</div>
            </div>
           
        </div> 
        <div class="cateBtn" v-if="activeName=='1'">
                <el-button type="primary" @click="toAddSubmit">立即{{text1}}</el-button>
        </div>
    </div>
</template>

<script>
import { VueEditor } from "vue2-editor";
import forwardTable from '@/components/information/publicTable/forwardTable.vue';
import supportTable from '@/components/information/publicTable/supportTable.vue';
import commentList from '@/components/information/publicTable/commentList.vue';
export default {
  data() {
    return {
      activeName:'1',
        id:null,
      tit: "",
      text:'新增',
      text1:'添加',
      checkList: [],//发布对象
      categoryList:[],//发布类别
      fileList: [],
      dialogVisible: false,
      dialogImageUrl: "",
      detail:'',
      editorLoading:false , //富文本图片loading
      myHeaders: {
        "access-token": this.$store.state.token, //这里重新定义了请求头
        Authorization: this.$store.state.token,
        "user-id": this.$store.state.user_id
      },
      customToolbar: [
        [{ header: [false, 1, 2, 3, 4, 5, 6] }], //标题
        ["bold", "italic", "underline"], //加粗\斜体\下划线
        ["italic"], //斜体----也可以拆开来写，用于换位置顺序
        [{ align: "" }, { align: "center" }, { align: "right" }], //对齐
        [{ list: "ordered" }, { list: "bullet" }, { list: "check" }], //有序无序列表
        [{ background: [] }, { color: [] }], //背景色
        ["image", "link"], //图片、链接
        ["strike"], //作废（文字中间一横）
        ["underline"],
        ["clean"], //清楚格式（所谓去掉背景色这些花里胡巧）
        ["code"], //代码
        ["code-block"] //代码块
        // ['video'] //视频
      ],
      mediaType:'0',//媒体类型
      
      videoUrl:'',//视频连接
      videoId:'',//视频id
      videoFlag:false,
      videoUploadPercent:0,

      status:'0',//是否上架0否1是

      marketId:'',//卖场id
      marketList:[],
    };
  },
  components: {
    VueEditor,
    forwardTable,
    supportTable,
    commentList
  },
  mounted() {
      this.remoteMethod()
      this.id = this.$route.query.id
      if(this.id){
          this.viewDetail()
          this.text= '编辑'
          this.text1 = '保存'
      }
  },
  methods: {
      // 获取卖场列表
      remoteMethod(){
        this.$http.post('/api/root/Market/marketList').then(res=>{
          console.log(res,'卖场列表');
          if(res.code==1){
            this.marketList = res.data?res.data:[]
          }
        })
      },
      // 选择卖场
      selectMarket(){
        // this.getInfoList()
      },

    // 切换tabs
    handleClick(e){
      if(this.activeName == '2'){
        this.$refs.forwardFn.getForwardList()
      }else if(this.activeName == '3'){
        this.$refs.supportFn.getForwardList()
      }else if(this.activeName == '4'){
        this.$refs.commentFn.getCommentList()
      }
    },

    // 获取资讯详情
    viewDetail(){
        this.$http.post('/api/root/information/view',{id:this.id}).then(res=>{
            console.log(res,'资讯详情');
            if(res.code==1){
                this.tit = res.data.title;
                this.checkList = res.data.role?res.data.role.split(','):[];
                this.categoryList = res.data.category?res.data.category.split(','):[];
                this.detail = res.data.content;
                this.marketId = res.data.market_id?res.data.market_id:'';
                this.status = res.data.status.toString();
                this.mediaType = res.data.type.toString();
               if(res.data.type==1){
                  let imgArr = []
                  res.data.media.map(item=>{
                      imgArr.push({
                          url:item.path,
                          id:item.id
                      })
                  })
                  this.fileList = imgArr
               }else if(res.data.type==2){
                  this.videoUrl = res.data.media[0].path
                  this.videoId = res.data.media[0].id
               }
            }
        })
    },
    

    //   立即添加按钮
    toAddSubmit(){
        if(this.tit==''){
            this.$message.warning('请填写标题')
            return
        }else if(!this.checkList.length){
            this.$message.warning('请选择发布对象')
            return 
        }else if(this.detail==''){
            this.$message.warning('请填写资讯内容')
            return
        }else if(!this.categoryList.length){
            this.$message.warning('请选择发布类别')
            return
        }else if(this.marketId==''){
            this.$message.warning('请选择卖场')
            return
        }
        let media_id = []
        if(this.mediaType=='1'){
          this.fileList.map(item=>{
              if(item.response){
                  media_id.push(item.response.data.id)
              }else{
                  media_id.push(item.id)
              }
          })
        }else if(this.mediaType=='2'){
          media_id.push(this.videoId)
        }
        let params = {
            id:this.id,
            title:this.tit,
            content:this.detail,
            media:media_id.join(','),
            role:this.checkList.join(','),
            type:this.mediaType,
            status:this.status,
            category:this.categoryList.join(','),
            market_id:this.marketId
        }
        let url = this.id?'/api/root/Information/edit':'/api/root/Information/add';
        this.$http.post(url,params).then(res=>{
            console.log(res,'发布结果');
            if(res.code==1){
                this.$message.success(this.id?'修改成功':'发布成功');
                this.$router.back(1)
            }else{
                this.$message.warning(res.msg)
            }
        })
    },


    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleAvatarSuccess(res, file, fileList) {
      this.fileList = fileList;
      console.log(this.fileList, "上传图片");
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("上传商品图片大小不能超过 10MB!");
      }
      return isLt2M;
    },


    // 验证视频格式
      beforeUploadVideo(file) {
          if (
              [
              'video/mp4',
              'video/ogg',
              'video/flv',
              'video/avi',
              'video/wmv',
              'video/rmvb'
              ].indexOf(file.type) === -1
          ) {
              this.$message.error('请上传正确的视频格式')
              return false
          }
          const isLt2M = file.size / 1024 / 1024 < 100;
          if (!isLt2M) {
              this.$message.error('上传视频大小不能超过 100MB!');
          }
      },
      // 上传进度显示
      uploadVideoProcess(event, file, fileList) {
          console.log(event.percent, file, fileList)
          this.videoFlag = true
          this.videoUploadPercent = Math.floor(event.percent)
      },

      // 获取上传地址
      handleVideoSuccess(res, file) {
          this.videoFlag = false
          this.videoUploadPercent = 0
          console.log(res,file,'视频上传')
          this.videoUrl = file.response.data.url
          this.videoId = file.response.data.id
      },

      // 删除视频按钮
      closeVideo(){
          this.videoUrl = ''
          this.videoId = ''
      },
      format(percentage) {
        return percentage === 100 ? '上传中...' : `${percentage}%`;
      },

     //富文本上传图片
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      // let file = event.target.files[0];
      let isLtSize = file.size / 1024 / 1024 < 10;
      // console.log(isLtSize);
      if (!isLtSize) {
        this.$message.warning("上传文件不能超过 10MB!");
        return;
      }
      this.editorLoading = true
      let form = new FormData();
        form.append("file", file);
        this.$http
        .post("/api/client/base/uploadfile", form)
        .then(result => {
          // console.log(result);
          // 你上传路径返回的url
          let url = result.data.url;
          // console.log(url);
          Editor.insertEmbed(cursorLocation, "image", url);
          resetUploader();
          this.editorLoading = false
        })
        .catch(err => {
          // console.log(err);
          this.editorLoading = false
        });
    },
    // 返回按钮
    toBack() {
      this.$router.back(1);
    }
  }
};
</script>

<style lang="less" scoped>
@import "informationAdd.less";
</style>

